/**
 * 创建 IndexedDB 工具方法
 * @param {string} dbName - 数据库名称
 * @param {string} storeName - 对象存储名称
 * @returns {Object} - 返回包含操作方法的对象
 */
function createIndexedDBUtil(dbName, storeName) {
  let db;

  // 检查浏览器是否支持 IndexedDB
  const isIndexedDBSupported = () => {
    return "indexedDB" in window;
  };

  // 打开数据库
  const openDB = (version = 1) => {
    return new Promise((resolve, reject) => {
      if (!dbName) {
        reject(new Error("数据库名称不能为空"));
        return;
      }

      const request = indexedDB.open(dbName, version);

      request.onupgradeneeded = (event) => {
        db = event.target.result;
        if (!db.objectStoreNames.contains(storeName)) {
          const objectStore = db.createObjectStore(storeName, {
            keyPath: "id",
            autoIncrement: true,
          });
          // 为对象存储创建索引（假设你需要按 name 和 age 查询）
          objectStore.createIndex("name", "name", { unique: false });
          objectStore.createIndex("age", "age", { unique: false });
        }
      };

      request.onsuccess = (event) => {
        db = event.target.result;
        resolve(db);
      };

      request.onerror = (event) => {
        reject(event.target.error);
      };
    });
  };

  // 关闭数据库
  const closeDB = () => {
    if (db) {
      db.close();
      db = null;
    }
  };

  // 获取对象存储
  const getObjectStore = async (mode = "readonly") => {
    const database = await openDB();
    const transaction = database.transaction(storeName, mode);
    return transaction.objectStore(storeName);
  };

  // 添加单条数据
  const add = async (data) => {
    const store = await getObjectStore("readwrite");

    return new Promise((resolve, reject) => {
      const request = store.add(data);
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  };

  // 删除单条数据
  const remove = async (id) => {
    const store = await getObjectStore("readwrite");

    return new Promise((resolve, reject) => {
      const request = store.delete(id);
      request.onsuccess = () => resolve(id);
      request.onerror = () => reject(request.error);
    });
  };

  // 删除单条数据
  const removeAll = async () => {
    const store = await getObjectStore("readwrite");

    return new Promise((resolve, reject) => {
      const request = store.clear();
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  };

  // 更新数据
  const update = async (data) => {
    const store = await getObjectStore("readwrite");
    const dataArray = Array.isArray(data) ? data : [data];

    return Promise.all(
      dataArray.map((item) => {
        return new Promise((resolve, reject) => {
          const request = store.put(item);
          request.onsuccess = () => resolve(request.result);
          request.onerror = () => reject(request.error);
        });
      }),
    );
  };

  // 查询单条数据
  const get = async (id) => {
    const store = await getObjectStore();

    return new Promise((resolve, reject) => {
      const request = store.get(id);
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  };

  // 查询所有数据
  const getAll = async () => {
    const store = await getObjectStore();

    return new Promise((resolve, reject) => {
      const request = store.getAll();
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  };

  // 使用索引搜索
  const queryByKey = async (searchIndexName, keyValue) => {
    const store = await getObjectStore();
    const index = store.index(searchIndexName);

    return new Promise((resolve, reject) => {
      const request = index.get(keyValue);
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  };

  return {
    isIndexedDBSupported,
    openDB,
    closeDB,
    add,
    update,
    remove,
    removeAll,
    get,
    getAll,
    queryByKey,
  };
}

export default createIndexedDBUtil;
